package com.atguigu.msm.controller;

import com.atguigu.msm.service.MsmService;
import com.atguigu.msm.utils.RandomUtil;
import com.atguigu.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
public class MsmController {

    @Resource
    private MsmService msmService;
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @GetMapping("/send/{phone}")
    public R sendMsg(@PathVariable("phone") String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        code = RandomUtil.getFourBitRandom();
        Map<String,String> map=new HashMap<>();
        map.put("code",code);
        boolean isSuccess=msmService.send(map,phone);
        if(isSuccess){
            redisTemplate.opsForValue().set(phone,code,1, TimeUnit.DAYS);
            return R.ok();
        }else {
            return R.error().message("发送短信失败");
        }

    }
}
